package com.example.myblog.util;


import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Wu YunXia
 * @Description: cookie
 * @Date: Created in 10:44 2020/11/30
 * @Modefied By:
 */
public class COOKIEUtil {
//    HttpServletRequest request;
//    HttpServletResponse response;



    /**
    * @Date 11:01 2020/11/30
    * @desc: 添加cookie
    */
    public static void addCookie(HttpServletResponse response,String value,String username,int maxAge){


        Cookie cookie = new Cookie("bUsername",value);
        cookie.setPath("/");
        cookie.setDomain("116.62.147.89");
        if(maxAge>0)  cookie.setMaxAge(maxAge);


        response.addCookie(cookie);

        Cookie cookie1 = new Cookie("curUsername",username);
        cookie1.setPath("/");
        cookie1.setDomain("116.62.147.89");
        if(maxAge>0)  cookie1.setMaxAge(maxAge);

        response.addCookie(cookie1);

//        System.out.println(response+"_________9a9280d81704b2d76efa7de4a5259c6a");


    }


    /**
    * @Date 11:02 2020/11/30
    * @desc: 获取cookie
    */
    public static Cookie getCookieByName(HttpServletRequest request,String name){
        Map<String,Cookie> cookieMap = ReadCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }
    }


    /**
    * @Date 11:03 2020/11/30
    * @desc: cookie封装到map
    */
    private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    /**
    * @Date 12:00 2020/11/30
    * @desc: 删除
    */

    public static Boolean delCookie(HttpServletResponse response,HttpServletRequest request,String name){
       Cookie cookie = new Cookie(name,"null");
       cookie.setMaxAge(0); //
       cookie.setPath("/");  // 相同路径
       response.addCookie(cookie);

        return true;
    }


}
